<template>
  <div id="microappbox"></div>
</template>

<script lang="ts" setup>
import {onMounted, onBeforeUnmount} from "vue";
import {ElMessage} from 'element-plus';
import {
  loadMicroApp, initGlobalState, MicroAppStateActions
} from 'qiankun';
import router from "@/router";
import type {AppMo} from "@/service/entity/AppMo";
import {useRoute} from "vue-router";
import {openApp} from "@/service/AppManager";
import {setAppToken} from "@/utils/setToken";

let microApp = undefined

const state = {
  off: false
};

// 初始化 state
const actions: MicroAppStateActions = initGlobalState(state);

actions.onGlobalStateChange((state, prev) => {
  // state: 变更后的状态; prev 变更前的状态
  console.log('主应用检测到state变更：', state, prev);
  if (state.off) {
    if (microApp) {
      console.log('退出应用而卸载应用')
      microApp.unmount()
      microApp = undefined
    }
    router.replace('/myAppList')
  }
});

onMounted(async () => {
  if (microApp) return
  const route = useRoute()
  const q = route.query
  const openToken = q.openToken
  if (openToken) {
    const authKey = q.authKey
    delete q.openToken
    delete q.authKey
    for (let k in q) {
      localStorage.setItem(k, `${q[k]}`)
    }

    await mountOpenApp(openToken as string, authKey as string)
  } else {
    await mountDefaultApp()
  }
})

const mountOpenApp = async (openToken: string, authKey: string) => {
  const res = await openApp(openToken, authKey)
  if (!res) return
  const appSymbol = res.rootPath.split('/')[2]
  setAppToken(appSymbol, res.token)
  localStorage.setItem(`${appSymbol}-appName`, res.appName)
  localStorage.setItem(`${appSymbol}-roleLevel`, `${res.roleLevel}`)
  if (res.isAdmin) {
    localStorage.setItem(`${appSymbol}-isAdmin`, '1')
  } else {
    localStorage.setItem(`${appSymbol}-isAdmin`, '0')
  }
  if (res.permStrs && res.permStrs.length) {
    localStorage.setItem(`${appSymbol}-permStrs`, res.permStrs.join(","))
  }
  if (res.roles) {
    localStorage.setItem(`${appSymbol}-roles`, JSON.stringify(res.roles))
  }
  if (res.menuList) {
    localStorage.setItem(`${appSymbol}-menuList`, JSON.stringify(res.menuList))
  }

  //======================兼容===========================

  setAppToken('', res.token)
  localStorage.setItem('appName', res.appName)
  localStorage.setItem('roleLevel', `${res.roleLevel}`)
  if (res.isAdmin) {
    localStorage.setItem('isAdmin', '1')
  } else {
    localStorage.setItem('isAdmin', '0')
  }
  if (res.permStrs && res.permStrs.length) {
    localStorage.setItem('permStrs', res.permStrs.join(","))
  }
  if (res.roles) {
    localStorage.setItem('roles', JSON.stringify(res.roles))
  }
  if (res.menuList) {
    localStorage.setItem('menuList', JSON.stringify(res.menuList))
  }
  localStorage.setItem('uname', res.uname)
  localStorage.setItem('uid', `${res.uid}`)
  localStorage.setItem('name', res.name)

  //=================================================
  let entry = `//${res.frontIp}:${res.frontPort}`
  if (res.nginxBasePath) {
    if (res.nginxBasePath.startsWith('/')) {
      entry += res.nginxBasePath
    } else {
      entry += `/${res.nginxBasePath}`
    }
  }
  microApp = loadMicroApp({
    name: res.appName,
    entry: entry,
    container: '#microappbox',
    props: {
      hideLogout: true,
      parentActions: actions
    }
  })

  const routeRes = await router.push(res.rootPath.replace('#/', '/'))
}

const mountDefaultApp = async () => {
  const appInfo = localStorage.getItem('defaultAppInfo')
  if (!appInfo) {
    ElMessage.error('无效应用')
    router.go(-1)
    return
  }
  const app: AppMo = JSON.parse(appInfo)
  // let entry = `//${app.frontIp}:${app.frontPort}`
  let entry = ''
  if (app.nginxBasePath) {
    if (app.nginxBasePath.startsWith('/')) {
      entry += app.nginxBasePath
    } else {
      entry += `/${app.nginxBasePath}`
    }
  }
  microApp = loadMicroApp({
    name: app.appName,
    entry: entry,
    container: '#microappbox',
    props: {
      parentActions: actions
    }
  })

  // setDefaultMountApp(app.activeRule)
}

onBeforeUnmount(() => {
  if (microApp) {
    console.log('页面关闭而卸载应用')
    microApp.unmount()
    microApp = undefined
  }
})
</script>

<style lang="scss" scoped>
#microappbox {
  width: 100%;
  height: 100%;
}
</style>